<?php

namespace app\admin\controller;

use think\Controller;
use think\Log;
use think\db;
use think\Request;
use app\admin\model\Adminrole;
use app\admin\model\Admin;

class CommonController extends Controller {

    const DEFAULTIMG_1 = 'default/user3-128x128.jpg';

    public function _initialize() {
        $request = Request::instance();
        $url = $request->url(true);
        $module = $request->module(); //模块名
        $controller = $request->controller(); //控制器名
        $action = $request->action(); //方法名

        $token = Request::instance()->header('token');
        if (empty($token)) {
            $token = input('param.token');
        }

        $adminRow = Admin::where('token', '=', $token)->where('valid_time', '>', date('Y-m-d H:i:s'))->field('role,token')->find();
        if (empty($adminRow)) {
            echo $this->ajaxReturn(4, '登录超时请重新登录', null);
            die;
        }

        $no_auth_action = ['Public']; //不需要验证的方法

        if (!in_array($controller, $no_auth_action)) {
            $roleID = Adminrole::where('module', '=', $module)
                    ->where('controller', '=', $controller)
                    ->where('action', '=', $action)
                    ->value('id');

            $adminRoleID = $adminRow['role'];
            $adminRoleID = explode(",", $adminRoleID);
            if (!in_array($roleID, $adminRoleID)) {
                echo $this->ajaxReturn(5, '您没有权限操作', null);
                die;
            }
        }
    }

    /*
     * 返回json
     */

    public function ajaxReturn($code, $msg, $data) {
        $array = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
//        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,token");
        header('Access-Control-Allow-Methods: GET, POST, PUT,OPTIONS');
        header('Content-Type:application/json; charset=utf-8');
        return json_encode($array);
    }

}
